import webview
import time
import json
import requests
from pyautogui import size
import pygetwindow
import random
from bs4 import BeautifulSoup
import ctypes
from win32 import win32gui, win32print
from win32.lib import win32con
import wppAction
import os


with open("now_wpp.json","r")as f:
    wpp_data=json.load(f)
    f.close()
char_id = wpp_data["char"]
with open("char/"+char_id+"/char_inf.json","r")as f:
    char_data = json.load(f)
# 时间段对话信息整理
th_dict = {
    "th_6-11":[],
    "th_11-14":[],
    "th_14-18":[],
    "th_18-22":[],
    "th_22-6":[]
}
for c_index in char_data["chat"]:
    c=char_data["chat"][c_index]
    print(c)
    if c["type"] in th_dict:
        th_dict[c["type"]].append(c_index)
# 天气对话信息整理
weather_dict={
    "weather_sunny":[],
    "weather_rain":[],
    "weather_thunderstorm":[],
    "weather_snow":[],
    "weather_cloudy":[]
}
for c_index in char_data["chat"]:
    c=char_data["chat"][c_index]
    if c["type"] in weather_dict:
        weather_dict[c["type"]].append(c_index)

# 生日对话信息整理
birthday_notes = []
had_play_birthday = False
for c_index in char_data["chat"]:
    c=char_data["chat"][c_index]
    if c["type"] == "birthday":
        birthday_notes.append(c_index)

def get_weather():
    headers = {'Content-Type':'application/json',  'User-Agent':'Mozilla/5.0 (Windows NT 10.0; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36','Referer':'https://www.baidu.com/s?ie=UTF-8&wd=ip%E6%9F%A5%E8%AF%A2'}
    url = 'https://www.baidu.com/s?ie=UTF-8&wd=%E5%A4%A9%E6%B0%94'
    response = requests.get(url,headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    class_name = "cu-mr-base"
    elements = soup.find_all(class_=class_name)
    return elements[0].get_text()
def play_chat(c_name):
    print(c_name)
    window.show()
    print("播放"+c_name)
    window.evaluate_js("play_chat('"+c_name+"')")
    time.sleep(char_data["chat"][c_name]["voice_time"]/1000)
    time.sleep(1)
    window.hide()
def random_result(gl):
    if random.randint(0,100) <= int(gl):
        return True
    else:
        return False
def play_time_note():
    try:
        print("播放时间段对话")
        h = int(time.strftime("%H"))
        # m = int(time.strftime("%M"))
        if h>=22 or h<6:
            if len(th_dict["th_22-6"])>0:
                play_chat(random.sample(th_dict["th_22-6"],1)[0])
        elif h>=6 and h<11:
            if len(th_dict["th_6-11"])>0:
                play_chat(random.sample(th_dict["th_6-11"],1)[0])
        elif h>=11 and h<14:
            if len(th_dict["th_11-14"])>0:
                play_chat(random.sample(th_dict["th_11-14"],1)[0])
        elif h>=14 and h<18:
            if len(th_dict["th_14-18"]):
                play_chat(random.sample(th_dict["th_14-18"],1)[0])
        elif h>=18 and h<22:
            if len(th_dict["th_18-22"]):
                play_chat(random.sample(th_dict["th_18-22"],1)[0])
    except:
        pass
def play_weather_note():
    try:
        wt = get_weather()
        print(wt)
        if "雨" in wt:
            play_chat(random.sample(weather_dict["weather_rain"],1)[0])
        elif "雪" in wt:
            play_chat(random.sample(weather_dict["weather_snow"],1)[0])
        elif "晴" in wt or "多云" in wt:
            play_chat(random.sample(weather_dict["weather_sunny"],1)[0])
        elif "雷" in wt:
            play_chat(random.sample(weather_dict["weather_thunderstorm"],1)[0])
        elif "阴" in wt:
            play_chat(random.sample(weather_dict["weather_cloudy"],1)[0])
        print(wt)
    except:
        pass
def play_birthday_note():
    try:
        print("播放生日对话")
        if os.path.exists("cookies.json"):
            cookies = wppAction.read_jsonFile("cookies.json")
            r = requests.get("http://127.0.0.1:8001/user_data/privacy/",cookies=cookies)
            data = json.loads(str(r.content,"utf-8"))
            if data["success"]==True and data["login"]==True:
                if r.status_code==200:
                    now_date = time.strftime("%m-%d",time.localtime())
                    origin_birthday = data["data"]["personality_inf"]["birthday"]
                    user_birthday = origin_birthday[-5:len(origin_birthday)]
                    print(user_birthday)
                    if now_date == user_birthday:
                        play_chat(random.sample(birthday_notes,1)[0])
    except:
        pass
def play_hello_note(data):
    rs = random.sample(data,1)[0]
    play_chat("chat",rs,True,"hello")
def action(aData):
    if random_result(aData["gl"])==True:
        if aData["action"] == "TimeHello":
            play_time_note()
        elif aData["action"]=="weather":
            play_weather_note()
        else:
            if "play-chat:" in aData["action"]:
                dialog_name = aData["action"].split(":")[1]
                play_chat(dialog_name)
        return True
    return False
def run_char():
    global had_play_birthday
    time.sleep(3)
    window.hide()
    
    # 寻找并执行“开启时”事件
    for r in char_data["rule"]:
        if r["type"]=="when_start":
            print(r)
            action(r)

    action_Record={}
    last_match = None
    last_allMatch = None

    while True:
        r_range = 0
        for r in char_data["rule"]:
            if r["type"]=="timeMatch":
                h = int(time.strftime("%H"))
                m = int(time.strftime("%M"))
                tar_h = int(r["inf"].split(":")[0])
                tar_m = int(r["inf"].split(":")[1])
                if h==tar_h and m>=tar_m:
                    record_code = str(r_range)+"tm"+r["inf"]
                    if record_code in action_Record:
                        if h>tar_h and m>tar_m:
                            del action_Record[record_code]
                            print("删除一个时间触发任务记录")
                        continue
                    else:
                        if action(r) == True:
                            action_Record[record_code]=time.time()
            elif r["type"]=="win_titleAllMatch":
                record_code = str(r_range)+"wam"+r["inf"]
                if record_code in action_Record:
                    if int(time.time())-int(action_Record[record_code]) > 60*60:
                        del action_Record[record_code]
                    else:
                        continue
                else:
                    active_title = pygetwindow.getActiveWindowTitle()
                    if active_title == r["inf"]:
                        if action(r) == True:
                            action_Record[record_code]=time.time()
                        last_allMatch = active_title
                    else:
                        if last_allMatch != None:
                            last_allMatch = None
            elif r["type"]== "win_titleMatch":
                record_code = str(r_range)+"wm"+r["inf"]
                if record_code in action_Record:
                    if int(time.time())-int(action_Record[record_code]) > 60*60:
                        del action_Record[record_code]
                    else:
                        continue
                else:
                    active_title = pygetwindow.getActiveWindowTitle()
                    if r["inf"] in active_title:
                        if action(r) ==  True:
                            action_Record[record_code]=time.time()
                        last_match = active_title
                    else:
                        if last_match != None:
                            last_match = None
            elif r["type"]=="birthday":
                if had_play_birthday == False:
                    had_play_birthday = True
                    play_birthday_note()
            r_range += 1
        time.sleep(5)



class API:
    def get_charData(self):
        with open("now_wpp.json","r")as f:
            wpp_data=json.load(f)
            f.close()
        char_id = wpp_data["char"]
        with open("char/"+char_id+"/char_inf.json","r")as f:
            char_data = json.load(f)
        return {"success":True,"wpp_data":char_data}
    def get_charId(self):
        with open("now_wpp.json","r")as f:
            wpp_data=json.load(f)
            f.close()
        return wpp_data["char"]
api = API()
def get_screen_size():
    hDC = win32gui.GetDC(0)
    # 横向分辨率
    w = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)
    # 纵向分辨率
    h = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)
    return w, h
def get_windows_scaling_factor():
    try:
        # 调用 Windows API 函数获取缩放比例
        user32 = ctypes.windll.user32
        user32.SetProcessDPIAware()
        scaling_factor = user32.GetDpiForSystem()
 
        # 计算缩放比例
        return scaling_factor / 96.0
    except Exception as e:
        print("获取缩放比例时出错:", e)
        return 1.50

ow,oh = get_screen_size()
print(ow,oh)

win_w = int(ow*0.25)
win_h = int(oh*0.25)

win_offset_x = int(ow*0.73)
win_offset_y = int(oh*0.75)

window = webview.create_window(
    'char_view',
    "char_set.html",
    width=win_w,
    height=win_h,
    x=win_offset_x,
    y=win_offset_y,
    text_select=False,
    js_api=api,
    transparent=True,
    frameless=True,
    on_top=True,
)
webview.start(run_char)
